<template>
  <el-dialog
    :title="mode === 'add' ? '新增部门' : '编辑部门'"
    :visible.sync="isShow"
    width="500"
  >
    <el-form ref="form" label-width="100px" :model="form" :rules="rules">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model.trim="form.name" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model.trim="form.code" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="form.manager" @focus="focusEvent">
          <el-option v-for="i in userList" :key="i.id" :value="i.username">{{
            i.username
          }}</el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="form.introduce" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div style="text-align: center">
        <el-button @click="isShow = false">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import {
  sysUserSimple,
  companyDepartmentPost,
  companyDepartmentPut
} from '@/api/departments'

export default {
  name: 'DialogItem',
  props: {
    //  部门原始数据
    initList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      mode: 'add', //  add添加  edit //编辑
      isShow: false,
      userList: [],
      dialogItem: '', // 点击树形结构时每一项数据
      form: {
        name: '',
        code: '',
        manager: '',
        introduce: '',
        pid: ''
      },
      rules: {
        name: [
          { required: true, message: '必填', trigger: 'change' },
          {
            validator: (rules, value, callback) => {
              let _res = ''
              if (this.mode === 'add') {
                _res = this.initList.filter((item) => {
                  return this.dialogItem.id === item.pid
                })
              } else {
                _res = this.initList.filter((item) => {
                  return (
                    //  同级部门pid相同
                    this.dialogItem.pid === item.pid && item.id !== this.form.id
                  )
                })
              }
              const _result = _res.some((item) => {
                return item.name === value
              })
              _result ? callback(new Error('部门名字重复')) : callback()
            },
            trigger: 'change'
          }
        ],
        code: [
          { required: true, message: '必填', trigger: 'change' },
          {
            validator: (rule, value, callback) => {
              let result = ''
              if (this.mode === 'add') {
                result = this.initList.some((item) => {
                  return item.code === value
                })
              } else {
                result = this.initList.some((item) => {
                  return item.code === value && item.id !== this.form.id
                })
              }
              result ? callback(new Error('部门编码重复')) : callback()
            }
          }
        ],
        manager: [{ required: true, message: '必填', trigger: 'change' }],
        introduce: [{ required: true, message: '必填', trigger: 'change' }]
      }
    }
  },
  watch: {
    isShow: {
      //  关闭弹框 初始化表单
      handler(newval) {
        if (!newval) {
          // this.isShow=false
          this.$refs.form.resetFields()
          this.form = {
            name: '',
            code: '',
            manager: '',
            introduce: '',
            pid: ''
          }
        }
      }
    }
  },
  mounted() {
    this.$bus.$on('show', (msg, item, mode = 'add') => {
      this.isShow = msg
      this.dialogItem = item
      this.mode = mode
      if (mode === 'edit') {
        this.form = JSON.parse(JSON.stringify(item))
      }
      console.log('item', item)
    })
  },
  beforeCreate() {
    this.$bus.$off('show')
  },
  methods: {
    //  打开下拉菜单

    async focusEvent() {
      const res = await sysUserSimple()
      this.userList = res.data
      //   console.log('员工简易列表', res)
    },
    //  提交时表单验证
    submit() {
      // console.log('initList', this.initList)
      //   alert('hhah')
      this.$refs.form.validate(async(result) => {
        if (result) {
          if (this.mode === 'add') {
            this.form.pid = this.dialogItem.id
            await companyDepartmentPost(this.form)
            this.isShow = false
            this.$message.success('添加成功')
            this.$emit('getData')
          } else {
            await companyDepartmentPut(this.form)
            this.isShow = false
            this.$message.success('编辑成功')
            this.$emit('getData')
          }
        }
      })
    }
  }
}
</script>

<style></style>
